<template>
  <div class="publish-container">
    <div class="publish-card">
      <h2>发布新帖</h2>
      <form @submit.prevent="submitPost">
        <!-- 标题输入 -->
        <div class="form-group">
          <label>标题</label>
          <input 
            v-model="post.title" 
            type="text" 
            required
            placeholder="请输入标题（建议20字以内）"
            :disabled="isSubmitting"
          />
          <p v-if="errors.title" class="error-text">{{ errors.title }}</p>
        </div>

        <!-- 富文本编辑器（重构交互逻辑） -->
        <div class="form-group editor-group">
          <label>内容</label>
          <div class="editor-container">
            <!-- 工具栏 -->
            <div class="editor-toolbar">
              <button 
                type="button" 
                @click="formatText('bold')" 
                title="加粗"
                :disabled="isSubmitting"
              >
                <b>B</b>
              </button>
              <button 
                type="button" 
                @click="formatText('italic')" 
                title="斜体"
                :disabled="isSubmitting"
              >
                <i>I</i>
              </button>
              <button 
                type="button" 
                @click="formatText('underline')" 
                title="下划线"
                :disabled="isSubmitting"
              >
                <u>U</u>
              </button>
              <button 
                type="button" 
                @click="insertLink" 
                title="插入链接"
                :disabled="isSubmitting"
              >
                <i class="fas fa-link"></i>
              </button>
              <button 
                type="button" 
                @click="insertImage" 
                title="插入图片"
                :disabled="isSubmitting"
              >
                <i class="fas fa-image"></i>
              </button>
            </div>
            
            <!-- 编辑器核心 -->
            <div 
              contenteditable="true" 
              ref="editor" 
              @input="syncEditorContent"
              @focus="handleEditorFocus"
              @blur="handleEditorBlur"
              class="editor-content"
              :class="{ 'empty': !post.htmlContent && !isEditorFocused }"
              :disabled="isSubmitting"
            >
              <!-- 初始化占位符优化 -->
              <template v-if="!post.htmlContent && !isEditorFocused">
                <p class="placeholder">请输入内容...</p>
              </template>
            </div>
          </div>
          <p v-if="errors.content" class="error-text">{{ errors.content }}</p>
        </div>

        <!-- 分类选择 -->
        <div class="form-group">
          <label>分类</label>
          <select 
            v-model="post.category"
            required
            :disabled="isSubmitting"
          >
            <option value="">请选择分类</option>
            <option value="announcement">校园公告</option>
            <option value="news">校园新闻</option>
            <option value="notice">通知</option>
            <option value="academic">学术动态</option>
            <option value="activity">校园活动</option>
          </select>
          <p v-if="errors.category" class="error-text">{{ errors.category }}</p>
        </div>

        <!-- 标签管理（交互优化） -->
        <div class="form-group">
          <label>标签</label>
          <div class="tag-input">
            <input 
              v-model="tagInput" 
              @keyup.enter="addTag"
              placeholder="添加标签（回车确认）"
              :disabled="isSubmitting"
            />
            <div class="tag-list">
              <span 
                v-for="(tag, index) in post.tags" 
                :key="index" 
                class="tag-item"
                @click="removeTag(index)"
                :disabled="isSubmitting"
              >
                {{ tag }} 
                <i class="fas fa-times-circle tag-remove"></i>
              </span>
            </div>
          </div>
          <p v-if="errors.tags" class="error-text">{{ errors.tags }}</p>
        </div>

        <!-- 封面上传（可视化优化） -->
        <div class="form-group">
          <label>封面图片</label>
          <div class="image-upload">
            <label class="upload-label" :disabled="isSubmitting">
              <input 
                type="file" 
                accept="image/*"
                @change="handleImageUpload"
                :disabled="isSubmitting"
              />
              <div class="image-upload-box">
                <i class="fas fa-cloud-upload-alt"></i>
                <p>点击上传封面图（建议尺寸：800x450像素）</p>
              </div>
            </label>
            <div v-if="post.imageName" class="image-name">
              已选择: {{ post.imageName }}
            </div>
            <p class="hint-text">支持JPG/PNG格式，大小不超过5MB</p>
            <p v-if="errors.image" class="error-text">{{ errors.image }}</p>
          </div>
        </div>

        <!-- 附件上传（支持文档） -->
        <div class="form-group">
          <label>附件（可选，支持txt/docx/pdf等）</label>
          <div class="image-upload">
            <label class="upload-label" :disabled="isSubmitting">
              <input 
                type="file" 
                accept=".txt,.doc,.docx,.pdf,.md,.xls,.xlsx,.ppt,.pptx,.zip,.rar,.7z,.csv,.json,.xml,.log"
                @change="handleFileUpload"
                :disabled="isSubmitting"
              />
              <div class="image-upload-box">
                <i class="fas fa-paperclip"></i>
                <p>点击上传文档/附件（最大10MB）</p>
              </div>
            </label>
            <div v-if="post.fileName" class="image-name">
              已选择: {{ post.fileName }}
            </div>
            <p class="hint-text">支持txt/docx/pdf/zip等，大小不超过10MB</p>
            <p v-if="errors.file" class="error-text">{{ errors.file }}</p>
          </div>
        </div>

        <!-- 操作按钮组 -->
        <div class="button-group">
          <button 
            type="button" 
            class="save-draft"
            @click="saveDraft"
            :disabled="isSubmitting || !canSaveDraft"
          >
            {{ draftSaved ? '草稿已保存' : '保存草稿' }}
          </button>
          
          <button 
            type="submit" 
            class="publish-button"
            :disabled="isSubmitting || !canPublish"
          >
            {{ isSubmitting ? '发布中...' : '发布' }}
          </button>
        </div>

        <!-- 服务端错误提示 -->
        <div v-if="error" class="server-error">
          {{ error }}
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import apiClient from '@/utils/api.js'
import { ElMessage } from 'element-plus'
import { computed, nextTick, onMounted, reactive, ref } from 'vue'

// 响应式数据
const post = reactive({
  title: '',
  htmlContent: '',   // 富文本HTML内容
  rawContent: '',    // 纯文本内容
  category: '',
  imageName: '',
  imageFile: null,
  fileName: '',      // 新增：附件名
  file: null,        // 新增：附件文件对象
  tags: []
})

const tagInput = ref('')
const isSubmitting = ref(false)
const isEditorFocused = ref(false)
const errors = ref({})
const error = ref(null)
const draftSaved = ref(false)
const editor = ref(null) // 编辑器DOM引用

// 表单状态计算
const canSaveDraft = computed(() => 
  post.title.trim() || post.htmlContent.trim()
)

const canPublish = computed(() => 
  !isSubmitting.value && 
  Object.keys(errors.value).length === 0 && 
  post.title.trim() && 
  post.htmlContent.trim() && 
  post.category && 
  post.tags.length > 0 && 
  post.imageFile
)

// 表单验证（拆分逻辑，更易维护）
function validateTitle() {
  if (!post.title.trim()) return '标题不能为空'
  if (post.title.length > 50) return '标题不能超过50个字符'
  return ''
}

function validateContent() {
  if (!post.rawContent.trim()) return '内容不能为空'
  return ''
}

function validateCategory() {
  return post.category ? '' : '请选择分类'
}

function validateTags() {
  if (post.tags.length === 0) return '至少添加一个标签'
  if (post.tags.length > 5) return '最多添加5个标签'
  return ''
}

function validateImage() {
  return post.imageFile ? '' : '请上传封面图片'
}

function validateFile() {
  if (post.file && post.file.size > 10 * 1024 * 1024) return '附件不能超过10MB'
  return ''
}

function validateForm() {
  errors.value = {
    title: validateTitle(),
    content: validateContent(),
    category: validateCategory(),
    tags: validateTags(),
    image: validateImage(),
    file: validateFile()
  }
  return Object.values(errors.value).every(err => !err)
}

// 标签操作（增强校验）
function addTag() {
  const tag = tagInput.value.trim()
  if (!tag) return

  if (post.tags.includes(tag)) {
    errors.value.tags = '标签已存在'
    return
  }

  if (post.tags.length >= 5) {
    errors.value.tags = '最多添加5个标签'
    return
  }

  post.tags.push(tag)
  tagInput.value = ''
  errors.value.tags = ''
}

function removeTag(index) {
  post.tags.splice(index, 1)
  errors.value.tags = '' // 移除后重置错误
}

// 封面上传（增强错误处理）
function handleImageUpload(event) {
  const file = event.target.files[0]
  if (!file) return

  const validTypes = ['image/jpeg', 'image/png']
  if (!validTypes.includes(file.type)) {
    errors.value.image = '仅支持JPG/PNG格式'
    post.imageName = ''
    post.imageFile = null
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    errors.value.image = '文件大小不能超过5MB'
    post.imageFile = null
    return
  }

  post.imageName = file.name
  post.imageFile = file
  errors.value.image = ''
}

// 附件上传（增强错误处理）
function handleFileUpload(event) {
  const file = event.target.files[0]
  if (!file) return
  // 支持的类型
  const validTypes = [
    'text/plain', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/pdf', 'application/zip', 'application/x-7z-compressed', 'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/json',
    'text/csv', 'application/xml', 'text/markdown', 'application/x-rar-compressed', 'text/x-log'
  ]
  if (!validTypes.includes(file.type) && !file.name.match(/\.(txt|docx?|pdf|zip|rar|7z|csv|json|xml|log|md|xls|xlsx|ppt|pptx)$/i)) {
    errors.value.file = '不支持的文件类型'
    post.fileName = ''
    post.file = null
    return
  }
  if (file.size > 10 * 1024 * 1024) {
    errors.value.file = '附件不能超过10MB'
    post.file = null
    return
  }
  post.fileName = file.name
  post.file = file
  errors.value.file = ''
}

// 富文本编辑器核心逻辑（重构）
function syncEditorContent() {
  if (!editor.value) return

  // 同步HTML和纯文本内容
  post.htmlContent = editor.value.innerHTML
  post.rawContent = editor.value.textContent

  // 自动保存草稿（优化触发条件）
  if (!draftSaved.value && canSaveDraft.value) {
    saveDraft()
  }
}

function handleEditorFocus() {
  isEditorFocused.value = true
  // 清除初始化占位符
  const placeholder = editor.value.querySelector('.placeholder')
  if (placeholder) {
    editor.value.removeChild(placeholder)
  }
}

function handleEditorBlur() {
  isEditorFocused.value = false
  // 恢复占位符（内容为空时）
  if (!post.htmlContent.trim()) {
    nextTick(() => {
      const placeholder = document.createElement('p')
      placeholder.className = 'placeholder'
      placeholder.textContent = '请输入内容...'
      editor.value.appendChild(placeholder)
    })
  }
}

function formatText(command) {
  if (!editor.value) return
  document.execCommand(command, false)
}

function insertLink() {
  const url = prompt('请输入链接地址:')
  if (url) {
    document.execCommand('createLink', false, url)
  }
}

function insertImage() {
  const url = prompt('请输入图片URL:')
  if (url) {
    document.execCommand('insertImage', false, url)
  }
}

// 草稿功能（增强可靠性）
function saveDraft() {
  const draft = {
    title: post.title,
    htmlContent: post.htmlContent,
    category: post.category,
    tags: post.tags
  }
  localStorage.setItem('postDraft', JSON.stringify(draft))
  draftSaved.value = true

  // 2秒后重置状态
  setTimeout(() => {
    draftSaved.value = false
  }, 2000)
}

function loadDraft() {
  const draft = JSON.parse(localStorage.getItem('postDraft'))
  if (draft) {
    post.title = draft.title
    post.htmlContent = draft.htmlContent
    post.category = draft.category
    post.tags = draft.tags || []

    // 确保DOM渲染后再设置编辑器内容
    nextTick(() => {
      if (editor.value) {
        editor.value.innerHTML = draft.htmlContent
        // 同步纯文本内容
        post.rawContent = editor.value.textContent
      }
    })
  }
}

// 提交发布（增强异常处理）
async function submitPost() {
  if (!validateForm()) return
  isSubmitting.value = true
  error.value = null
  try {
    const formData = new FormData()
    formData.append('title', post.title)
    formData.append('content', post.rawContent)
    formData.append('htmlContent', post.htmlContent)
    formData.append('category', post.category)
    formData.append('tags', JSON.stringify(post.tags))
    if (post.imageFile) {
      formData.append('image', post.imageFile)
    }
    if (post.file) {
      formData.append('file', post.file)
    }
    const response = await apiClient.post('/posts', formData)
    if (response.data.success) {
      ElMessage.success('发布成功！')
      // 清空表单
      Object.assign(post, {
        title: '',
        htmlContent: '',
        rawContent: '',
        category: '',
        imageName: '',
        imageFile: null,
        fileName: '',
        file: null,
        tags: []
      })
      tagInput.value = ''
      // 草稿清理
      localStorage.removeItem('postDraft')
      draftSaved.value = false
    } else {
      error.value = response.data.message || '发布失败，请重试'
    }
  } catch (err) {
    error.value = '发布失败，请检查网络连接'
    console.error(err)
  } finally {
    isSubmitting.value = false
  }
}

// 初始化草稿加载
onMounted(() => {
  loadDraft()
})
</script>

<style scoped>
.publish-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f4f4f9;
}

.publish-card {
  background-color: #fff;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 800px;
}

h2 {
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  color: #333;
  text-align: center;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: #333;
}

input[type="text"],
select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
  color: #333;
}

input[type="file"] {
  display: none;
}

.upload-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  border: 2px dashed #007bff;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-label:hover {
  border-color: #0056b3;
}

.image-upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  border: 2px dashed #007bff;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.image-upload-box:hover {
  border-color: #0056b3;
}

.image-name {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  color: #666;
}

.hint-text {
  font-size: 0.875rem;
  color: #666;
  margin-top: 0.5rem;
}

.error-text {
  font-size: 0.875rem;
  color: #e74c3c;
  margin-top: 0.5rem;
}

.tag-input {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.tag-input input {
  flex: 1;
  min-width: 200px;
  margin-right: 0.5rem;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 0.5rem;
}

.tag-item {
  display: flex;
  align-items: center;
  background-color: #007bff;
  color: #fff;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  margin-right: 0.5rem;
  margin-bottom: 0.5rem;
  cursor: pointer;
}

.tag-remove {
  margin-left: 0.25rem;
  font-size: 0.875rem;
}

.editor-group {
  position: relative;
}

.editor-toolbar {
  position: absolute;
  top: -40px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: flex-start;
  background-color: #fff;
  padding: 0.5rem;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.editor-toolbar button {
  background: none;
  border: none;
  color: #007bff;
  font-size: 1rem;
  margin-right: 0.5rem;
  cursor: pointer;
  transition: color 0.3s;
}

.editor-toolbar button:hover {
  color: #0056b3;
}

.editor-content {
  min-height: 200px;
  padding: 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #fafafa;
  font-size: 1rem;
  color: #333;
  overflow-y: auto;
}

.editor-content.empty {
  color: #999;
}

.placeholder {
  color: #999;
  font-style: italic;
  pointer-events: none;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.save-draft {
  background-color: #f39c12;
  color: #fff;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  flex: 1;
  margin-right: 0.5rem;
}

.save-draft:hover {
  background-color: #e67e22;
}

.publish-button {
  background-color: #007bff;
  color: #fff;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  flex: 1;
}

.publish-button:hover {
  background-color: #0056b3;
}

.server-error {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: #f2dede;
  color: #a94442;
  border: 1px solid #ebccd1;
  border-radius: 4px;
  text-align: center;
}
</style>